<script setup>
import { useEchartsOperations } from '@/hooks/useEchartsOperations.js'
import { getTrendData } from '@/api/index.js'
import { computed, ref } from 'vue'

const { chart, chartInstance, updateChart, fetchData, data } =
  useEchartsOperations()

// 选择的类型数组
const selectTypes = computed(() => {
  return data.value.type?.filter((item) => item.key !== selectType.value)
})
// 选择的类型
const selectType = ref('map')
// 点击事件
const onclick = (key) => {
  selectType.value = key
  updateChart.value()
  showChoice.value = false
}
// 展示选择
const showChoice = ref(false)

const showTitle = computed(() => {
  return data.value[selectType.value].title
})

updateChart.value = () => {
  const showData = data.value[selectType.value] // 选择的数据
  const colorArr1 = [
    'rgba(11, 168,44, 0.5)',
    'rgba(44,110,255,0.5)',
    'rgba(22,242,217,0.5)',
    'rgba(254, 33, 30, 0.5)',
    'rgba(250, 105, 0, 0.5)'
  ]
  const colorArr2 = [
    'rgba(11,168,44,0)',
    'rgba(44,110,255,0)',
    'rgba(22,242,217,0)',
    'rgba(254,33,30,0)',
    'rgba(250,105,0,0)'
  ]
  const option = {
    grid: {
      top: '35%',
      left: '3%',
      right: '4%',
      bottom: '1%',
      containLabel: true // 包含坐标轴的刻度标签
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: showData.data.map((item) => item.name),
      left: 20,
      top: '15%'
    },
    xAxis: {
      type: 'category',
      data: showData.data.map((item) => item.name),
      boundaryGap: false
    },
    yAxis: {
      type: 'value'
    },
    series: showData.data.map((item, index) => ({
      name: item.name,
      type: 'line',
      data: item.data,
      stack: '总量',
      itemStyle: {
        color: colorArr1[index]
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            {
              offset: 0,
              color: colorArr1[index]
            },
            {
              offset: 1,
              color: colorArr2[index]
            }
          ],
          global: false
        }
      }
    }))
  }
  chartInstance.value.setOption(option)
}

fetchData.value = async () => {
  const res = await getTrendData()
  data.value = res.data
}
</script>

<template>
  <div class="title absolute z-10 c-white pos-left-2xl pos-top-2xl">
    <span>{{ showTitle }}</span>
    <span
      class="iconfont m-l-2 cursor-pointer"
      @click="showChoice = !showChoice"
      >&#xe6eb;
    </span>
    <div v-show="showChoice">
      <div
        v-for="item in selectTypes"
        :key="item.key"
        @click="onclick(item.key)"
        class="cursor-pointer m-l-2"
      >
        {{ item.text }}
      </div>
    </div>
  </div>
  <div class="com-container">
    <div class="com-chart" ref="chart"></div>
  </div>
</template>

<style scoped></style>
